<?php

namespace app\admin\controller\shopro;

use app\admin\model\shopro\user\Account;
use think\Db;
use think\Exception;
use think\exception\HttpResponseException;
use addons\shopro\exception\ShoproException;
use app\admin\model\shopro\Withdraw as WithdrawModel;
use app\admin\model\shopro\WithdrawLog as WithdrawLogModel;
use app\admin\model\shopro\user\User as UserModel;
use app\admin\model\Admin as AdminModel;
use addons\shopro\service\Withdraw as WithdrawLibrary;
use addons\shopro\library\Operator;

/**
 * 兑换
 */
class Withdraw extends Common
{

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new WithdrawModel;
        $this->logModel = new WithdrawLogModel;
        $this->accountModel = new Account;
    }



    /**
     * 兑换列表
     */
    public function index()
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }
        $model=$this->model->sheepFilter();

        $withdraws = $model->with(['user'])->paginate($this->request->param('list_rows', 10));


        $total_amount=  $model->sheepFilter()->sum('amount');   //->field('SUM(amount) as total_amount,SUM(paid_fee) as total_paid_fee,SUM(des_tokens) as total_des_tokens')->find();

        $total_paid_fee=  $model->sheepFilter()->sum('paid_fee');
        $total_des_tokens=$model->sheepFilter()->sum('des_tokens');
        $count=[
            'total_amount' =>$total_amount,
            'total_paid_fee'=>$total_paid_fee,
            'total_des_tokens'=>$total_des_tokens,
        ];

        $data=[
            'withdraws'=>$withdraws,
            'count'=>$count
        ];



        $this->success('获取成功', null, $data);
    }


    public function export()
    {
        $cellTitles = [
            'id' => 'Id',
            'nickname' => '申请用户',
            'currency_type' => '货币类型',
            'amount' => '兑换数量',
            'charge_fee' => '费率/手续费',
            'to_shopping' => '购物积分',
            'paid_fee' => '实际兑换',
            'des_tokens' => '销毁通证',
            'withdraw_info' => '接受信息',
            'withdraw_type' => '兑换方式',
            'createtime' => '申请时间',
            'updatetime' => '上次操作时间',
            'status' => '状态',
        ];

        // 数据总条数
        $total = $this->model->sheepFilter()->count();
        if ($total <= 0) {
            $this->error('导出数据为空');
        }

        $export = new \addons\shopro\library\Export();
        $params = [
            'file_name' => '提现明细列表',
            'cell_titles' => $cellTitles,
            'total' => $total,
            'is_sub_cell' => false,
        ];

        $total_commission = 0;
        $result = $export->export($params, function ($pages) use (&$total_commission, $total) {
            $datas = $this->model->sheepFilter()->with(['user'])
                ->limit((($pages['page'] - 1) * $pages['list_rows']), $pages['list_rows'])
                ->select();

            $datas = collection($datas);
            $datas->each(function ($order) {
            })->toArray();

            $newDatas = [];
            foreach ($datas as &$reward) {
                $winfo = '';
                foreach ($reward['withdraw_info'] as $ww => $vv) {
                    $winfo .= "$ww:$vv;\r\n";
                }
                $data = [
                    'id' => $reward['id'],
                    'currency_type' => $reward['currency_type'] == 1 ? '消费券' : ($reward['currency_type'] == 2 ? '福利券' : '金豆'),
                    'nickname' => (string)$reward['user']['nickname'] . ' ',
                    'amount' => $reward['amount'],
                    'charge_fee' => $reward['charge_rate'] * 100 . '%/' . $reward['charge_fee'],
                    'paid_fee' => $reward['paid_fee'],
                    'withdraw_type' => $reward['withdraw_type'] == 'bank' ? '银行卡' : ($reward['withdraw_type'] == 'wechat' ? '微信' : '支付宝'),
                    'status' => $reward['status'] == -1 ? '已拒绝' : ($reward['status'] == 0 ? '审核中' : ($reward['status'] == 1 ? '处理中' : '已处理')),
                    'createtime' => $reward['createtime'],
                    'updatetime' => $reward['updatetime'],
                    'des_tokens' => $reward['des_tokens'],
                    'to_shopping' => $reward['to_shopping'],
                    'withdraw_info' => $winfo
                ];

                $newDatas[] = $data;
            }

//            $total_commission += array_sum(array_column($newDatas, 'commission'));
//
//            if ($pages['is_last_page']) {
//                $newDatas[] = ['id' => "总数：" . $total . "；总数量：￥" . $total_commission .  "；"];
//            }
            return $newDatas;
        });

        $this->success('导出成功' . (isset($result['file_path']) && $result['file_path'] ? '，请在服务器: “' . $result['file_path'] . '” 查看' : ''), null, $result);
    }


    /**
     * 兑换日志
     */
    public function log($id)
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $logs = $this->logModel->where('withdraw_id', $id)->order('id desc')->select();
        $morphs = [
            'user' => UserModel::class,
            'admin' => AdminModel::class,
            'system' => AdminModel::class
        ];
        $logs = morph_to($logs, $morphs, ['oper_type', 'oper_id']);
        $logs = $logs->toArray();

        // 解析操作人信息
        foreach ($logs as &$log) {
            $log['oper'] = Operator::info($log['oper_type'], $log['oper'] ?? null);
        }
        $this->success('获取成功', null, $logs);
    }


    /**
     * 更多收款方式
     * @param $id
     * @return string|void
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function info($id)
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $logs = $this->accountModel->where('user_id', $id)->order('id desc')->select();
        $this->success('获取成功', null, $logs);
    }


    public function handle($id)
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $params = $this->request->param();
        $action = $params['action'] ?? null;
        $refuse_msg = $params['refuse_msg'] ?? '';
        if ($action == 'refuse' && !$refuse_msg) {
            $this->error('请输入拒绝原因');
        }

        $ids = is_array($id) ? $id : explode(',', $id);
        foreach ($ids as $key => $id) {
            Db::startTrans();
            try {
                $withdraw = $this->model->lock(true)->where('id', $id)->find();
                if (!$withdraw) {
                    $this->error(__('No Results were found'));
                }
                $withdrawLib = new WithdrawLibrary($withdraw->user_id);

                switch ($action) {
                    case 'agree':
                        $withdraw = $withdrawLib->handleAgree($withdraw);
                        break;
                    case 'agree&withdraw':
                        $withdraw = $withdrawLib->handleAgree($withdraw);
                        $withdraw = $withdrawLib->handleWithdraw($withdraw);
                        break;
                    case 'withdraw':
                        $withdraw = $withdrawLib->handleWithdraw($withdraw);
                        break;
                    case 'refuse':
                        $withdraw = $withdrawLib->handleRefuse($withdraw, $refuse_msg);
                        break;
                }

                Db::commit();
            } catch (ShoproException $e) {
                Db::commit();       // 不回滚，记录错误日志
                $this->error($e->getMessage());
            } catch (HttpResponseException $e) {
                $data = $e->getResponse()->getData();
                $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
                $this->error($message);
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }

        $this->success('处理成功');
    }
}
